{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "c26705c2-368b-4067-8565-3c292290fe87",
   "metadata": {},
   "outputs": [],
   "source": [
    "def detOfMtr(x):\n",
    "    if \"[[\" not in str(x) or \"]]\" not in str(x) or type(x)!=list:\n",
    "        return \"做不到哦\"\n",
    "    elif len(x)==1:\n",
    "        return x[0][0]\n",
    "    elif len(x)==2:\n",
    "        return x[0][0]*x[1][1]-x[1][0]*x[0][1]\n",
    "    else:\n",
    "        res=sum(((-1)**c)*x[0][c]*detOfMtr([row[:c]+row[c+1:]for row in x[1:]])for c in range(len(x)))\n",
    "        #错误代码：res=sum(((-1)**c)*x[0][c]*detOfMtr([[row[:c]+row[c+1:]]for row in x[1:]])for c in range(len(x)))\n",
    "        #错因：detOfMtr函数内的列表多了一层导致索引溢出\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "3e7c9224-67bd-4a7a-bc54-3e5b9cad35d9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "detOfMtr([[1,2,3],[4,5,6],[7,8,8]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "8bbd7021-9648-4438-a0fd-cbf25954b109",
   "metadata": {},
   "outputs": [],
   "source": [
    "def adj(x):\n",
    "    if type(detOfMtr(x))==str:\n",
    "        return \"不存在伴随矩阵\"\n",
    "    else:\n",
    "        result=[[((-1)**(i+c))*detOfMtr([row[:c]+row[c+1:] for row in x[:i] + x[i+1:]]) for i in range(len(x))]for c in range(len(x))]\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "c34971e4-b773-45cf-a813-52c8f4651153",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[-8, 8, -3], [10, -13, 6], [-3, 6, -3]]"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "adj([[1,2,3],[4,5,6],[7,8,8]])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
